package com.machinecontroller.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Path;
import android.media.MediaPlayer;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.machinecontroller.R;
import com.machinecontroller.adapter.ImageAdapter;
import com.machinecontroller.adapter.ManagerAdapter;
import com.machinecontroller.constant.FileConstant;
import com.machinecontroller.constant.McConfig;
import com.machinecontroller.constant.UrlConstant;
import com.machinecontroller.model.ConfigModel;
import com.machinecontroller.model.ResultModel;
import com.machinecontroller.service.GuardService;
import com.machinecontroller.service.HeartService;
import com.machinecontroller.service.UpdateService;
import com.machinecontroller.utils.BitmapUtil;
import com.machinecontroller.utils.DevUtil;
import com.machinecontroller.utils.FileUtil;
import com.machinecontroller.utils.GsonUtil;
import com.machinecontroller.utils.Logger;
import com.machinecontroller.utils.SpUtil;
import com.machinecontroller.utils.ToastUtil;
import com.sunshine.retrofit.HttpBuilder;
import com.sunshine.retrofit.HttpUtil;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.download.DownloadListener;
import com.tencent.bugly.beta.download.DownloadTask;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.machinecontroller.ui.ManagerActivity.APP_EXIT_ALL;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final int APP_MANAGER = 10001;
    private ViewPager mVpAd;
    private ImageView mIvSetting;
    private List<Uri> mImages = new ArrayList<>();
    private List<String> mVideoPaths = new ArrayList<>();
    private List<Integer> mResImages = new ArrayList<>();
    public final MainHandler mHandler = new MainHandler(this);
    private ImageAdapter mAdapter;
    private LinearLayout mDoctLayout;
    public static boolean isForeground = false;
    private ConfigModel mConfig;
    private VideoView mVvAd;
    private int currentVideo;//记录当前播放的视频
    private boolean forceQuitApp = false;//是否强制退出app
    private Timer updataTimer; //更新线程

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideSystemUI();
        setContentView(R.layout.activity_main);
        initData();
        initImgFromRes();
        initView();
        initResource();
        initCheckUpdate();
    }


    /**
     * 初始化资源，控制显示的视频或图片
     */
    private void initResource() {
        if (!McConfig.MC_IS_SUPORT_VIDEO) {
            showViewFloper();
        } else {
            showVideoPLayer();
        }
    }

    /**
     * 显示视频循环播放
     */
    private void showVideoPLayer() {
        mVvAd.setVisibility(View.VISIBLE);
        mVpAd.setVisibility(View.GONE);
        mDoctLayout.setVisibility(View.GONE);
        initVideoView();
    }

    /**
     * 显示图片广告轮播
     */
    private void showViewFloper() {
        initViewPager();
        addResourceFromSD();
        initDots(mImages.size());
        mVvAd.setVisibility(View.GONE);
        mDoctLayout.setVisibility(View.GONE);
        mVpAd.setVisibility(View.VISIBLE);
        mDoctLayout.setVisibility(View.VISIBLE);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 定时检查更新，temp
     */
    private void initCheckUpdate() {
        Beta.registerDownloadListener(new DownloadListener() {
            @Override
            public void onReceive(DownloadTask task) {

                Logger.e("aaa", task.getSaveFile().getAbsoluteFile().getPath());
            }

            @Override
            public void onCompleted(DownloadTask task) {
                Logger.e("aaa", task.getSaveFile().getAbsoluteFile().getPath());
//                doService();
//                updataTimer.cancel();
//                Beta.installApk(task.getSaveFile());

                SpUtil.putAppPath(getApplicationContext(),task.getSaveFile().getAbsoluteFile().getPath());
//                Intent i1 = new Intent(getApplication(), UpdateService.class);
//                getApplication().startService(i1);

            }

            @Override
            public void onFailed(DownloadTask task, int code, String extMsg) {
            }
        });
        updataTimer = new Timer();
        updataTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 4000;
                mHandler.sendMessage(msg);
            }
        }, McConfig.MC_UPDATE_TIME, McConfig.MC_UPDATE_TIME);
    }


    /**
     * 初始化视频播放器
     */
    private void initVideoView() {
        if (initVideoPathFromSD()) {
            if (mVideoPaths != null && mVideoPaths.size() > 0) {
                autoPlayerVideo();
            }
        } else {
            McConfig.MC_IS_SUPORT_VIDEO = false;
            showViewFloper();
        }
    }

    /**
     * 初始化视频文件的路径
     */
    private boolean initVideoPathFromSD() {
        File file = new File(McConfig.MC_VIDEO_PATH);
        if (!file.exists()) {
//            Toast.makeText(this, "视频文件不存在", Toast.LENGTH_SHORT).show();
            Logger.e(TAG, "视频文件不存在");
            return false;
        }
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
//            Toast.makeText(this, "视频文件不存在", Toast.LENGTH_SHORT).show();
            Logger.e(TAG, "视频文件不存在");
            return false;
        }
        for (int i = 0; i < files.length; i++) {
            Logger.e(TAG, files[i].getPath());
            mVideoPaths.add(files[i].getPath());
        }
        return true;
    }

    /**
     * 初始化设备的配置信息，将信息保存到缓存中。
     */
    private void initDevInfo() {
        ConfigModel configModel = new ConfigModel.Builder().
                setRegistrationId((String) SpUtil.get(getApplicationContext(), McConfig.MC_REGISTRATION_ID_NAME, "")).
                setPortNum(McConfig.MC_PORT_NUM).
                setImgPath(McConfig.MC_IMG_PATH).
                setVideoPath(McConfig.MC_VIDEO_PATH).
                setDevId(DevUtil.getDeviceId(getApplicationContext())).
                setContainerNum(DevUtil.getImei(getApplicationContext())).
                setViewfliperTime(McConfig.MC_VIEWFLIPER_TIME).
                setServiceCheckTime(McConfig.MC_CHECK_ACTVITY_START_TIME).
                setSuportVideo(McConfig.MC_IS_SUPORT_VIDEO).
                setForbidNotice(McConfig.MC_IS_FORBID_NOTICE).
                build();
        SpUtil.putConfigModel(getApplicationContext(), configModel);
    }

    /**
     * 启动守护线程
     */
    private void startService() {
        if (!forceQuitApp) {
            Logger.e(TAG, "启动服务");
            Intent i1 = new Intent(MainActivity.this, GuardService.class);
            startService(i1);
        }
    }

    /**
     * 启动守护线程
     */
    private void stopService() {
        Logger.e(TAG, "停止服务");
        forceQuitApp = true;
        Intent i1 = new Intent(MainActivity.this, GuardService.class);
        stopService(i1);
    }

    /**
     * 设置数据
     */
    private void initData() {
        mConfig = SpUtil.getConfigModel(getApplicationContext());
        initDevInfo();
        Map<String, String> map = new HashMap<>();
        String imei = DevUtil.getImei(getApplicationContext());
//        https://github.com/hust-MC/SlienceInstall.git
        map.put("devid", TextUtils.isEmpty(imei) ? "" : imei);
        map.put("version", DevUtil.getVersion(getApplicationContext()));
        new HttpBuilder(UrlConstant.API_CONFIG_DEV_INFO)
                .params(map)
                .params("key", "value")
                .tag(this)//需要取消请求的tag
                .success(str -> {//请求成功返回的数据
                    Log.e(TAG, str);
                    ResultModel model = GsonUtil.praseModel(str, ResultModel.class);
                    if (model != null) {
                        if (model.getCode().equals("0")) {
                            if (model.getResult() != null) {
                                McConfig.MC_VIEWFLIPER_TIME = Long.parseLong(model.getResult().getCarouselTime());
                                McConfig.MC_CHECK_ACTVITY_START_TIME = Long.parseLong(model.getResult().getKanmengou());
                                McConfig.MC_UPDATE_TIME = Long.parseLong(model.getResult().getHotTime());
                                McConfig.MC_HEART_TIME = Long.parseLong(model.getResult().getHeartTime());
                                initDevInfo();
                                //初始化视频、更新信息
                                initConfig();
                                return;
                            }
                        }
                    }
                    Logger.e(TAG, "数据返回异常");
                    initConfig();
                })
                .error(e -> {//请求失败返回的数据
                    Log.e(TAG, "数据返回异常 ==> " + e.toString());
                    initConfig();
                })
                .get();

    }

    /**
     * 初始化配置信息
     */
    private void initConfig() {
        initResource();
        initCheckUpdate();
        initHeartService();
    }

    /**
     * 开启心跳服务
     */
    private void initHeartService() {
        Intent i1 = new Intent(MainActivity.this, HeartService.class);
        startService(i1);
    }

    /**
     * 隐藏标题栏，以及状态栏。
     */
    private void hideSystemUI() {
        getSupportActionBar().hide();//隐藏标题
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//屏幕常亮
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                | View.SYSTEM_UI_FLAG_IMMERSIVE);//隐藏状态栏
    }

    /**
     * 初始化默认图片
     */
    private void initImgFromRes() {
        mResImages.add(R.mipmap.bg_01);
        mResImages.add(R.mipmap.bg_02);
        mResImages.add(R.mipmap.bg_03);
        mResImages.add(R.mipmap.bg_04);
        mResImages.add(R.mipmap.bg_05);
        mResImages.add(R.mipmap.bg_06);
        mResImages.add(R.mipmap.bg_07);
        mResImages.add(R.mipmap.bg_08);
    }

    int a = 0;

    /**
     * 初始化界面
     */
    private void initView() {
        mVpAd = (ViewPager) findViewById(R.id.vp_ad);
        mVvAd = (VideoView) findViewById(R.id.vv_ad);
        mIvSetting = (ImageView) findViewById(R.id.iv_setting);
        mIvSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                a++;
                ToastUtil.show(getApplicationContext(), "aaaa+" + a, Toast.LENGTH_SHORT);
            }
        });
        //
// mIvSetting.setOnLongClickListener(view -> {
//            ToastUtil.show(getApplicationContext(), "进入系统设置页面", Toast.LENGTH_SHORT);
//            stopService();
//            startActivityForResult(new Intent(MainActivity.this, ManagerActivity.class), APP_MANAGER);
//            return false;
//        });
        mDoctLayout = (LinearLayout) findViewById(R.id.ll_doct);
    }

    /**
     * 添加资源从sd卡中
     */
    private void addResourceFromSD() {
        File file = new File(FileConstant.APP_PATH + FileConstant.FILE_IMG_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        File[] files = file.listFiles();
        if (files == null) {
            addResourceFromApp();
            return;
        }
        if (files.length > 0) {
            mImages.clear();
            for (int i = 0; i < files.length; i++) {
                mImages.add(Uri.fromFile(files[i]));
            }
        } else {
            addResourceFromApp();
        }
    }

    /**
     * 添加资源，从默认图片中
     */
    private void addResourceFromApp() {
        mImages.clear();
        for (int i = 0; i < mResImages.size(); i++) {
            mImages.add(Uri.parse("res://com.machinecontroller/" + mResImages.get(i)));
        }
    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        mAdapter = new ImageAdapter(this, mImages);
        mVpAd.setAdapter(mAdapter);
        mVpAd.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                setCurrentDot(arg0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        /**
         * 轮播的线程
         */
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 3000;
                mHandler.sendMessage(msg);
            }
        }, McConfig.MC_VIEWFLIPER_TIME, McConfig.MC_VIEWFLIPER_TIME);

    }

    /**
     * 初始化轮播图下面的圆点
     */
    private void initDots(int count) {
        mDoctLayout.removeAllViews();
        for (int i = 0; i < count; i++) {
            TextView dot = (TextView) LayoutInflater.from(this).inflate(R.layout.item_doct,
                    mDoctLayout, false);
            mDoctLayout.addView(dot);
        }
        setCurrentDot(mVpAd.getCurrentItem());
    }

    /**
     * 设置轮播图下面的圆点
     */
    private void setCurrentDot(int position) {
        position = position % mImages.size();
        Object obj = mDoctLayout.getTag();
        if (obj != null && mDoctLayout.getChildAt((Integer) obj) != null) {
            mDoctLayout.getChildAt((Integer) obj).setSelected(false);
        }
        if (mDoctLayout.getChildAt(position) != null) {
            mDoctLayout.getChildAt(position).setSelected(true);
        }
        mDoctLayout.setTag(position);
    }

//    /**
//     * 本地存储图片的线程
//     */
//    private class ImageSaveThread extends Thread {
//
//
//        @Override
//        public void run() {
//            super.run();
//            int saveTimes = 0;
//            String filePath = FileConstant.APP_PATH + FileConstant.FILE_IMG_PATH + File.separator;
//            File file = new File(filePath);
//            File[] files = file.listFiles();
//            if (files.length > mResImages.size()) {
//                for (int i = 0; i < files.length; i++) {
//                    files[i].delete();
//                }
//            }
//            for (int i = 0; i < mResImages.size(); i++) {
//                InputStream inputStream = MainActivity.this.getResources().openRawResource(mResImages.get(i));
//                Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);
//                Boolean isSave = BitmapUtil.saveBitmap2JPEG(mBitmap, FileConstant.APP_PATH + FileConstant.FILE_IMG_PATH + File.separator, FileConstant.FILE_IMG_NAME + i + ".jpeg");
//                Log.e(MainActivity.class.getSimpleName(), "save img====>" + isSave);
//                if (isSave) {
//                    saveTimes++;
//                }
//                try {
//                    inputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            Message msg = Message.obtain();
//            msg.obj = saveTimes;
//            msg.what = 1000;
//            Looper.prepare();
//            mHandler.sendMessage(msg);
//            Looper.loop();
//            try {
//                this.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } finally {
//                this.interrupt();
//            }
//        }
//    }


    /**
     * 用于线程间交互
     */
    private static class MainHandler extends Handler {
        private WeakReference<MainActivity> mActivty;

        public MainHandler(MainActivity activity) {
            this.mActivty = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1000) {//图片
                Toast.makeText(mActivty.get(), "图片保存完成,成功保存" + msg.obj + "张", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 2000) {//视频
                Toast.makeText(mActivty.get(), "视频保存完成" + msg.obj, Toast.LENGTH_SHORT).show();
            } else if (msg.what == 3000) {
                int count = mActivty.get().mAdapter.getCount();
                int currentPosition = mActivty.get().mVpAd.getCurrentItem();
                if (mActivty.get().mAdapter.getCount() != 0) {
                    mActivty.get().mVpAd.setCurrentItem((currentPosition + 1) % count);
                }
            } else if (msg.what == 4000) { //请求到视屏接口，然后做操作
                Beta.checkUpgrade();
            }
        }

    }

    /**
     * 自动循环播放视频
     */
    private void autoPlayerVideo() {
        mVvAd.setVideoPath(mVideoPaths.get(currentVideo));
        mVvAd.requestFocus();
        try {

            mVvAd.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mVvAd.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mVideoPaths.size() == 1) {
                    mVvAd.start();
                } else {
                    nextVideo();//播放下一个视屏
                }
            }

            /**
             * 播放下一个视频
             */
            private void nextVideo() {
                currentVideo++;
                if (currentVideo == mVideoPaths.size()) {
                    currentVideo = 0;
                }
                mVvAd.setVideoPath(mVideoPaths.get(currentVideo));
                mVvAd.requestFocus();
                mVvAd.start();
            }
        });
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        initResource();
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startService();
    }

    @Override
    public void onLowMemory() {
        System.gc();
    }

    @Override
    public void onTrimMemory(int level) {
        System.gc();
        startService();
    }

    @Override
    protected void onStop() {
        super.onStop();
        startService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == APP_MANAGER) {
            forceQuitApp = data.getBooleanExtra(APP_EXIT_ALL, false);
            Logger.e(TAG, "forceQuitApp ==>" + forceQuitApp);
            if (forceQuitApp) {
                stopService();
                System.exit(0);
            }
        }
    }

    /**
     * 执行一次service命令，执行更新命令
     */
    private void doService() {
        // 自动升级
        // try {
        // Process install = Runtime.getRuntime().exec(new String[] { "su",
        // "-c","pm install -r /mnt/sdcard/CQYTJ.apk" });
        //// Process install = Runtime.getRuntime().exec(new String[]
        //// {"pm install -r /mnt/sdcard/CQYTJ.apk"});
        // install.waitFor();
        //// install2.waitFor();
        // if (install.exitValue() == 0) {
        // // Success 安装成功
        // Intent mintent = mc.getPackageManager()
        // .getLaunchIntentForPackage(
        // "aiom.w3studio.apps.android.sdhr");
        // mc.startActivity(mintent);
        // } else {
        // // Fail
        // }
        // } catch (IOException e) {
        // System.out.println(e.toString());
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // }

//        Intent mintent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("aiom.w3studio.apps.android.sdhr");
//        getApplicationContext().startActivity(mintent);
        // 传入参数
        Bundle bundle = new Bundle();
        bundle.putInt("op", 3001);
        bundle.putString("data", "可以传入的参数");
        Log.e("doService()", "启动自动升级");
        Intent intentService = new Intent("com.machinecontroller.service.UpdateService");
        intentService.putExtras(bundle);
        if (getApplicationContext() != null) {
            getApplicationContext().startService(intentService); // startService
        }
    }

}
